<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const allProducts = ref([])
const loading = ref(false)
const errorMessage = ref('')
const BASE_URL = 'http://localhost:3001'

// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(10)
const total = computed(() => allProducts.value.length)

// 计算当前页显示的商品
const products = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allProducts.value.slice(start, end)
})

// 获取商品列表
const fetchProducts = async () => {
  try {
    loading.value = true
    errorMessage.value = ''
    
    const token = localStorage.getItem('token')
    if (!token) {
      errorMessage.value = '未登录或登录已过期'
      return
    }

    const response = await fetch('http://localhost:3001/api/admin/products', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (!response.ok) {
      throw new Error('获取商品列表失败')
    }

    const data = await response.json()
    allProducts.value = Array.isArray(data) ? data : []
    
  } catch (error) {
    console.error('获取商品列表失败:', error)
    errorMessage.value = error.message || '网络错误，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 计算总页数
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// 生成页码数组
const pageNumbers = computed(() => {
  const pages = []
  const maxVisiblePages = 5
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2))
  let endPage = Math.min(totalPages.value, startPage + maxVisiblePages - 1)

  if (endPage - startPage + 1 < maxVisiblePages) {
    startPage = Math.max(1, endPage - maxVisiblePages + 1)
  }

  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  return pages
})

// 页码变化处理函数
const handlePageChange = (page) => {
  currentPage.value = page
  // 回到页面顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 格式化价格
const formatPrice = (price) => {
  return `¥${(price / 100).toFixed(2)}`
}

// 添加商品
const handleAddProduct = () => {
  router.push('/products/add')
}

// 编辑商品
const handleEdit = (product) => {
  currentEditProduct.value = { ...product }  // 创建一个副本
  showEditDialog.value = true
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    const token = localStorage.getItem('token')
    console.log(currentEditProduct.value.product_id);
    
    const response = await fetch(`${BASE_URL}/api/admin/products/${currentEditProduct.value.product_id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        name: currentEditProduct.value.name,
        description: currentEditProduct.value.description,
        price: currentEditProduct.value.price,
        stock: currentEditProduct.value.stock,
        category: currentEditProduct.value.category,
        status: currentEditProduct.value.status ? 1 : 0
      })
    })

    if (!response.ok) {
      throw new Error('更新失败')
    }

    const data = await response.json()
    
    if (data.success) {
      // 更新本地数据
      const index = allProducts.value.findIndex(p => p.product_id === currentEditProduct.value.product_id)
      if (index !== -1) {
        allProducts.value[index] = { ...currentEditProduct.value }
      }
      
      showEditDialog.value = false
      alert('更新成功')
    } else {
      throw new Error(data.message || '更新失败')
    }
  } catch (error) {
    console.error('更新商品失败:', error)
    alert(error.message || '更新失败')
  }
}

// 删除商品
const handleDelete = async (productId) => {
  if (!confirm('确定要删除这个商品吗？')) return
  
  
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${BASE_URL}/api/admin/products/${productId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (!response.ok) {
      throw new Error('删除失败')
    }

    const data = await response.json()
    if (data.success) {
      // 从本地数据中移除被删除的商品
      allProducts.value = allProducts.value.filter(p => p.product_id !== productId)
      alert('删除成功')
    } else {
      throw new Error(data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除商品失败:', error)
    alert(error.message || '删除失败')
  }
}

// 获取图片完整URL的方法
const getImageUrl = (url) => {
  try {
    if (!url) return '/default-product.png'
    
    // 如果是字符串，尝试解析为JSON
    const imageUrls = typeof url === 'string' ? JSON.parse(url) : url
    
    // 如果是数组且有元素
    if (Array.isArray(imageUrls) && imageUrls.length > 0) {
      // 打印调试信息
      // console.log('图片URL:', `${BASE_URL}${imageUrls[0]}`)
      return `${BASE_URL}${imageUrls[0]}`
    }
    
    return '/default-product.png'
  } catch (error) {
    console.error('处理图片URL失败:', error)
    return '/default-product.png'
  }
}

// 添加编辑相关的状态
const showEditDialog = ref(false)
const currentEditProduct = ref(null)

// 添加跳转方法
const goToOrders = () => {
  router.push('/orders')
}

// // 添加分类选项数组
// const categoryOptions = ref([
//   '食品', '服饰', '电子产品', '家居', '化妆品',
//   '厨卫电器', '个护健康', '运动户外', '汽车生活',
//   '儿童玩具', '男鞋', '女鞋', '其他'
// ])

// 添加搜索和筛选状态
const searchQuery = ref('')
const categoryFilter = ref('all')
const statusFilter = ref('all')

// 分类选项
const categoryOptions = [
  { value: 'all', label: '所有分类' },
  { value: '食品', label: '食品' },
  { value: '服饰', label: '服饰' },
  { value: '电子产品', label: '电子产品' },
  { value: '家居', label: '家居' },
  { value: '化妆品', label: '化妆品' },
  { value: '其他', label: '其他' }
]

// 状态选项
const statusOptions = [
  { value: 'all', label: '所有状态' },
  { value: '1', label: '上架' },
  { value: '0', label: '下架' }
]

// 计算过滤后的商品列表
const filteredProducts = computed(() => {
  return allProducts.value.filter(product => {
    // 搜索条件：商品名称包含搜索关键词
    const matchesSearch = product.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    
    // 分类筛选
    const matchesCategory = categoryFilter.value === 'all' || product.category === categoryFilter.value
    
    // 状态筛选
    const matchesStatus = statusFilter.value === 'all' || product.status.toString() === statusFilter.value
    
    return matchesSearch && matchesCategory && matchesStatus
  })
})

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = ''
  categoryFilter.value = 'all'
  statusFilter.value = 'all'
}

onMounted(() => {
  fetchProducts()
})
</script>

<template>
  <div class="products-page">
    <div class="page-header">
      <h2>商品管理</h2>
      <div class="header-actions">
        <button class="refresh-btn" @click="fetchProducts" :disabled="loading">
          <i class="fa-solid fa-rotate" :class="{ 'fa-spin': loading }"></i>
          {{ loading ? '加载中...' : '刷新' }}
        </button>
        <!-- <button class="add-btn" @click="handleAddProduct">
          <i class="fa-solid fa-plus"></i>
          添加商品
        </button> -->
        
      </div>
    </div>

    <!-- 添加搜索和筛选区域 -->
    <div class="filter-section">
      <div class="search-box">
        <i class="fa-solid fa-search"></i>
        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索商品名称..."
        />
      </div>
      
      <div class="filter-group">
        <select v-model="categoryFilter">
          <option 
            v-for="option in categoryOptions" 
            :key="option.value" 
            :value="option.value"
          >
            {{ option.label }}
          </option>
        </select>

        <select v-model="statusFilter">
          <option 
            v-for="option in statusOptions" 
            :key="option.value" 
            :value="option.value"
          >
            {{ option.label }}
          </option>
        </select>

        <button class="reset-btn" @click="resetFilters">
          <i class="fa-solid fa-rotate-left"></i>
          重置
        </button>
      </div>
    </div>

    <div v-if="errorMessage" class="error-message">
      <i class="fa-solid fa-circle-exclamation"></i>
      {{ errorMessage }}
    </div>

    <div class="products-table">
      <table>
        <thead>
          <tr>
            <th>订单编号</th>
            <th>商品名称</th>
            <th>商品图片</th>
            <th>订单详情</th>
            <th>价格</th>
            <th>分类</th>
            <th>库存</th>
            <th>创建时间</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading" class="loading-row">
            <td colspan="10" class="loading-cell">
              <i class="fa-solid fa-spinner fa-spin"></i>
              加载中...
            </td>
          </tr>
          <tr v-else-if="filteredProducts.length === 0" class="empty-row">
            <td colspan="10" class="empty-cell">
              {{ searchQuery || categoryFilter !== 'all' || statusFilter !== 'all' 
                ? '没有找到匹配的商品' 
                : '暂无商品数据' 
              }}
            </td>
          </tr>
          <tr v-else v-for="product in filteredProducts" :key="product.id">
            <td>{{ product.product_id }}</td>
            <td>{{ product.name }}</td>
            <td>
              <img 
                :src="getImageUrl(product.image_url)" 
                :alt="product.name"
                class="product-image"
                @error="(e) => {
                  console.error('图片加载失败:', e)
                  e.target.src = '/default-product.png'
                }"
              >
            </td>
            <td>{{ product.description }}</td>
            <td>{{ product.price }}</td>
            <td>{{ product.category }}</td>
            <td>{{ product.stock }}</td>
            <td>{{ product.created_at }}</td>
            <td>
              <span 
                class="status-tag"
                :class="product.status ? 'active' : 'inactive'"
              >
                {{ product.status ? '上架' : '下架' }}
              </span>
            </td>
            <td class="actions">
              <button 
                class="action-btn edit"
                @click="handleEdit(product)"
              >
                <i class="fa-solid fa-edit"></i>
                编辑
              </button>
              <button 
                class="action-btn delete"
                @click="handleDelete(product.product_id)"
              >
                <i class="fa-solid fa-trash"></i>
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination" v-if="filteredProducts.length > 0">
      <button 
        class="page-btn" 
        :disabled="currentPage === 1"
        @click="handlePageChange(currentPage - 1)"
      >
        <i class="fa-solid fa-chevron-left"></i>
      </button>
      
      <button 
        v-if="pageNumbers[0] > 1"
        class="page-btn"
        @click="handlePageChange(1)"
      >
        1
      </button>
      
      <span v-if="pageNumbers[0] > 2">...</span>
      
      <button 
        v-for="page in pageNumbers" 
        :key="page"
        class="page-btn"
        :class="{ active: page === currentPage }"
        @click="handlePageChange(page)"
      >
        {{ page }}
      </button>
      
      <span v-if="pageNumbers[pageNumbers.length - 1] < totalPages - 1">...</span>
      
      <button 
        v-if="pageNumbers[pageNumbers.length - 1] < totalPages"
        class="page-btn"
        @click="handlePageChange(totalPages)"
      >
        {{ totalPages }}
      </button>
      
      <button 
        class="page-btn"
        :disabled="currentPage === totalPages"
        @click="handlePageChange(currentPage + 1)"
      >
        <i class="fa-solid fa-chevron-right"></i>
      </button>
      
      <span class="page-info">
        共 {{ filteredProducts.length }} 条，每页 {{ pageSize }} 条
      </span>
    </div>

    <!-- 编辑弹窗 -->
    <div class="dialog-overlay" v-if="showEditDialog" @click="showEditDialog = false">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>编辑商品</h3>
          <button class="close-btn" @click="showEditDialog = false">
            <i class="fa-solid fa-times"></i>
          </button>
        </div>

        <div class="dialog-body" v-if="currentEditProduct">
          <div class="form-group">
            <label>商品名称</label>
            <input 
              type="text" 
              v-model="currentEditProduct.name"
              placeholder="请输入商品名称"
            >
          </div>

          <div class="form-group">
            <label>商品描述</label>
            <textarea 
              v-model="currentEditProduct.description"
              rows="3"
              placeholder="请输入商品描述"
            ></textarea>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>价格</label>
              <input 
                type="number" 
                v-model="currentEditProduct.price"
                min="0"
                step="0.01"
              >
            </div>

            <div class="form-group">
              <label>库存</label>
              <input 
                type="number" 
                v-model="currentEditProduct.stock"
                min="0"
              >
            </div>
          </div>

          <div class="form-group">
            <label>分类</label>
            <select 
              v-model="currentEditProduct.category"
              class="form-select"
            >
              <option 
                v-for="option in categoryOptions" 
                :key="option" 
                :value="option"
              >
                {{ option }}
              </option>
            </select>
          </div>

          <div class="form-group">
            <label class="checkbox-label">
              <input 
                type="checkbox" 
                v-model="currentEditProduct.status"
              >
              商品上架
            </label>
          </div>
        </div>

        <div class="dialog-footer">
          <button class="cancel-btn" @click="showEditDialog = false">取消</button>
          <button class="submit-btn" @click="handleEditSubmit">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.products-page {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.refresh-btn,
.add-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.refresh-btn {
  background: white;
  border: 1px solid #d1d5db;
}

.refresh-btn:hover:not(:disabled) {
  border-color: #1890ff;
  color: #1890ff;
}

.add-btn {
  background: #1890ff;
  color: white;
  border: none;
}

.add-btn:hover {
  background: #40a9ff;
}

.products-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 16px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: var(--border-radius);
  border: 1px solid var(--border-color);
}

.status-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: inline-block;
  width: 42px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-tag.active {
  background: #f6ffed;
  color: #52c41a;
}

.status-tag.inactive {
  background: #fff2f0;
  color: #ff4d4f;
}

.actions {
  display: flex;
  gap: 8px;
  margin-top: 37px;
  padding-bottom: 38px;
  justify-content: center;
}

.action-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  min-width: 60px;
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn.edit {
  background: #e6f7ff;
  color: #1890ff;
}

.action-btn.edit:hover {
  background: #bae7ff;
}

.action-btn.delete {
  background: #fff1f0;
  color: #ff4d4f;
}

.action-btn.delete:hover {
  background: #ffd4d4;
}

.action-btn i {
  font-size: 12px;
}

.loading-cell,
.empty-cell {
  text-align: center;
  padding: 32px;
  color: #6b7280;
}

.error-message {
  margin-bottom: 16px;
  padding: 12px;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 6px;
  color: #ff4d4f;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.dialog-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  color: #1f2937;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #6b7280;
  cursor: pointer;
  padding: 4px;
}

.dialog-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

label {
  display: block;
  margin-bottom: 8px;
  color: #4b5563;
  font-size: 14px;
}

input[type="text"],
input[type="number"],
textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  font-size: 14px;
}
/* 修改表格行的字体大小 */
tr {
  font-size: 12px; /* 设置更小的字体大小 */
}

/* 如果需要同时调整表头和内容的字体大小 */

/* 如果需要区分表头和内容的字体大小 */



.dialog-footer {
  padding: 16px 24px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.submit-btn,
.cancel-btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
}

.submit-btn {
  background: #2563eb;
  color: white;
  border: none;
}

.cancel-btn {
  background: white;
  border: 1px solid #e5e7eb;
  color: #4b5563;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 20px;
  padding: 20px 0;
  font-size: 14px;
}

.page-btn {
  min-width: 32px;
  height: 32px;
  padding: 0 8px;
  border: 1px solid #d1d5db;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-btn:hover:not(:disabled) {
  border-color: #1890ff;
  color: #1890ff;
}

.page-btn.active {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}

.page-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.page-info {
  margin-left: 16px;
  color: #6b7280;
}

.btn-text {
  border: none;
  background: none;
  color: #1890ff;
  cursor: pointer;
  padding: 4px 8px;
}

.btn-text:hover {
  background: rgba(24,144,255,0.1);
  border-radius: 4px;
}

/* 去掉按钮选中时的黑色边框 */
button:focus {
  outline: none;  /* 移除默认的焦点轮廓 */
}

.btn-text:focus,
.action-btn:focus,
.refresh-btn:focus,
.add-btn:focus {
  outline: none;
  box-shadow: none;  /* 移除可能的阴影效果 */
}

/* 如果想要一个更柔和的焦点效果，可以添加这个 */
.btn-text:focus-visible,
.action-btn:focus-visible,
.refresh-btn:focus-visible,
.add-btn:focus-visible {
  outline: 2px solid rgba(24, 144, 255, 0.2);
  outline-offset: 1px;
}

/* 去掉所有按钮的默认焦点轮廓 */
button {
  outline: none;  /* 移除默认的焦点轮廓 */
}

/* 为特定按钮类型移除焦点样式 */
.btn-text:focus,
.action-btn:focus,
.refresh-btn:focus,
.add-btn:focus,
.page-btn:focus,
.close-btn:focus,
.submit-btn:focus,
.cancel-btn:focus {
  outline: none;
  box-shadow: none;  /* 移除可能的阴影效果 */
}

/* 如果想要一个更柔和的焦点效果，可以添加这个（可选） */
.btn-text:focus-visible,
.action-btn:focus-visible,
.refresh-btn:focus-visible,
.add-btn:focus-visible,
.page-btn:focus-visible,
.close-btn:focus-visible,
.submit-btn:focus-visible,
.cancel-btn:focus-visible {
  outline: 2px solid rgba(24, 144, 255, 0.2);
  outline-offset: 1px;
}

/* 添加 select 样式 */
.form-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
}

.form-select:focus {
  outline: none;
  border-color: #2563eb;
}

.form-select option {
  padding: 8px;
}

/* 修改搜索和筛选区域的样式 */
.filter-section {
  margin-bottom: 24px;
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
  background: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.search-box {
  flex: 1;
  min-width: 200px;
  position: relative;
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #9ca3af;
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: white;
  color: #374151;
  font-size: 14px;
  transition: all 0.3s;
}

.search-box input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  outline: none;
}

.filter-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-group select {
  padding: 8px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: white;
  color: #374151;
  cursor: pointer;
  min-width: 120px;
  font-size: 14px;
  transition: all 0.3s;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%236B7280'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 8px center;
  background-size: 16px;
  padding-right: 32px;
}

.filter-group select:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  outline: none;
}

.reset-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: white;
  color: #374151;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.reset-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
  background: #e6f7ff;
}

.reset-btn i {
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .search-box {
    width: 100%;
  }
  
  .filter-group {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .filter-group select,
  .reset-btn {
    flex: 1;
    min-width: 0;
  }
}

/* 空状态消息样式 */
.empty-message {
  text-align: center;
  padding: 32px;
  color: #6b7280;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-top: 16px;
}
</style> 